﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using EZCRS.HCMS.Bll;
using EZCRS.HCMS.Bll.baseinfo;

using EZCRS.HCMS.Entity;
using EZCRS.HCMS.Bll.AIR;

namespace EZCRS.HCMS.Web.manage.AIR
{
    public partial class plan : ManageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (base.BasHotelId == 0)
                Response.Write(CFun.AlertMeg(Resources.Site.MustHotel, "back", ""));


            if (!IsPostBack)
            {
                CheckModule(69);
                
                string strStartDate = "";
                string strEndDate = "";
                string strSeasonID = "";
                string strPlanLists = "";

                string strRoomCode = "";
                string strPlanCodeLists = "";

                if (Request.QueryString["act"] != null)
                {
                    if (Request.Params["startdate"] != null)
                    {
                        strStartDate = Request.Params["startdate"];

                        if (Request.Params["enddate"] != null)
                        {
                            strEndDate = Request.Params["enddate"];
                        }
                    }

                    if (Request.Params["season"] != null)
                        strSeasonID = Request.Params["season"];

                    if (Request.Params["codes"] != null)
                        strPlanLists = Request.Params["codes"];

                    string strJSON = null;

                    if (Request.Params["plans"] != null && Request.Params["roomcode"] != null)
                    {
                        strPlanCodeLists = Request.Params["plans"];
                        strRoomCode = Request.Params["roomcode"];

                        strJSON = CheckRoomLevel(strStartDate, strEndDate, strPlanCodeLists, strRoomCode);
                    }
                    else
                        strJSON = CheckPlanLevel(strStartDate, strEndDate, strPlanLists, strSeasonID);

                    Response.Write(strJSON);
                    Response.End();

                }

                CFun.SetListControl(ddlStatus, Bllbase_info.getbaseinfo(baseinfotype.房间状态, CFun.CurrentLanguage()), "");
                CFun.SetListControl(cblWeek, HotelBaseInfo.Weebly(), "");

                foreach (ListItem li in cblWeek.Items) li.Selected = true;

                BindData();

                startdate.Attributes.Add("onclick", "event.cancelBubble=true;showCalendarTA('startdate',false,'startdate','startdate',null);");
                startdate.Attributes.Add("onblur", "if(!chkdate(this.value))this.value='yyyy-MM-dd';");

                enddate.Attributes.Add("onclick", "event.cancelBubble=true;showCalendarTA('enddate',false,'enddate','enddate',null);");
                enddate.Attributes.Add("onblur", "if(!chkdate(this.value))this.value='yyyy-MM-dd';");
            }
        }

        /// <summary>
        /// 基本数据绑定
        /// </summary>
        private void BindData()
        {
            BllRatePlan bllPlan = new BllRatePlan();

            int iRowCount = 0;

            int iLan = 0;

            if (base.CurrentLanguage != "zh-CN")
                iLan = 1;

            List<HCRS_Plan> lstPlan =
                bllPlan.getListByPage(base.BasPropertyId, 1, iLan, string.Empty, 1, 999, out iRowCount);

            if (lstPlan != null)
            {
                foreach (HCRS_Plan plan in lstPlan)
                    cblPlanList.Items.Add(new ListItem(plan.PlanCode, plan.PlanCode));
            }

            //rule

            BllHCRS_Cxlrule cxlrule = new BllHCRS_Cxlrule();
            BllH_guarule guarule = new BllH_guarule();


            List<HCRS_CxlRule> lstCxl = cxlrule.getitem("Property_id =" + base.BasPropertyId + " AND languagetype =" + iLan.ToString());

            ddlCxlRule.Items.Add(new ListItem("--Select--", ""));

            if (lstCxl != null)
            {
                foreach (HCRS_CxlRule cxl in lstCxl)
                    ddlCxlRule.Items.Add(new ListItem(cxl.Rule, cxl.Rule));
            }

            List<HCRS_GuaRule> lstGua = guarule.getitem("Property_id =" + base.BasPropertyId + " AND languagetype =" + iLan.ToString());

            ddlGuaRule.Items.Add(new ListItem("--Select--", ""));

            if (lstGua != null)
            {
                foreach (HCRS_GuaRule g in lstGua)
                    ddlGuaRule.Items.Add(new ListItem(g.Grule, g.Grule));
            }

            //season

            List<HCRS_Season> lst =
                bllPlan.getSeasonList(base.BasPropertyId, 1, 999, out iRowCount);

            ddlSeasonList.Items.Add(new ListItem("--Select--", ""));

            if (lst != null)
            {
                foreach (HCRS_Season obj in lst)
                    ddlSeasonList.Items.Add(new ListItem(obj.Name, obj.ID.ToString()));
            }

        }

        /// <summary>
        /// 保存:
        /// 提取数据库数据，并用数据转换器的LOAD方法装载原有数据
        /// 使用CREATE方法更新数据转换器中的临时数据，再进行序列化操作，
        /// 放入HOTEL_AIR对象中，
        /// 调用BLL的对象保存方法。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnsave_Click(object sender, EventArgs e)
        {

            DateTime dtStart = new DateTime();
            DateTime dtEnd = new DateTime();

            int[] iWeek = new int[7];

            int iPlanCount = 0;

            foreach (ListItem li in cblPlanList.Items)
            {
                if (li.Selected) iPlanCount++;
            }

            if (iPlanCount == 0)
            {
                Response.Write(CFun.AlertMeg(Resources.Site.NoRatePlanSelected, "back", ""));
                return;
            }

            if (Radio2.Checked)
            {

                if (!DateTime.TryParse(startdate.Value, out dtStart))
                {
                    Response.Write(CFun.AlertMeg(Resources.Site.DateFormatError, "back", ""));
                    return;
                }

                if (!DateTime.TryParse(enddate.Value, out dtEnd))
                {
                    Response.Write(CFun.AlertMeg(Resources.Site.DateFormatError, "back", ""));
                    return;
                }

                if (dtEnd < dtStart)
                {
                    Response.Write(CFun.AlertMeg(Resources.Site.DateFormatError, "back", ""));
                    return;
                }

                foreach (ListItem item in cblWeek.Items)
                {
                    if (item.Selected) iWeek[int.Parse(item.Value)] = 1; else iWeek[int.Parse(item.Value)] = 0;
                }

            }
            else
            {
                //季节段
                string strID = ddlSeasonList.SelectedValue;

                int iID = 0;
                int.TryParse(strID, out iID);

                BllRatePlan bllPlan = new BllRatePlan();

                HCRS_Season obj = bllPlan.getSeasonPlan(iID);

                if (obj != null)
                {
                    dtStart = obj.StartDate;
                    dtEnd = obj.EndDate;
                }

                string[] weeks = obj.Week.Split(',');

                //foreach (int i in iWeek) i = 0;

                for (int i = 0; i < iWeek.Length; i++) iWeek[i] = 0;

                foreach (string s in weeks)
                {
                    int day;
                    int.TryParse(s, out day);

                    if (day == 7)
                        iWeek[0] = 1;
                    else
                        iWeek[day - 1] = 1;

                }
            }

            //get data from page

            float fRate1 = 0f, fRate2 = 0f, fRate3 = 0f, fRate4 = 0f, fBFrate = 0f, fBed = 0f;
            int iBFnum = 0, iInventory = 0, iMin = 0, iMax = 0, iAdv = 0;

            float.TryParse(txtRate1.Text, out fRate1);
            float.TryParse(txtRate2.Text, out fRate2);
            float.TryParse(txtRate3.Text, out fRate3);
            float.TryParse(txtRate4.Text, out fRate4);

            float.TryParse(txtAddBed.Text, out fBed);
            float.TryParse(txtBFrate.Text, out fBFrate);

            int.TryParse(txtInventory.Text, out iInventory);

            int.TryParse(txtBFnum.Text, out iBFnum);

            int.TryParse(txtMin.Text, out iMin);
            int.TryParse(txtMax.Text, out iMax);
            int.TryParse(txtAdv.Text, out iAdv);

            string [] strRatePlans = new string[iPlanCount];

            int iIndex = 0;

            foreach (ListItem li in cblPlanList.Items)
            {
                if (li.Selected) { strRatePlans[iIndex] = li.Value; iIndex++; }
            }

            Bll.AIR.AIR air = new EZCRS.HCMS.Bll.AIR.AIR();


            bool b = air.SavePlanLevel(base.BasPropertyId, strRatePlans, fRate1, fRate2, fRate3, fRate4, fBed, cbBreakfast.Checked, fBFrate,
                iBFnum, iInventory, iMin, iMax, iAdv, ddlStatus.SelectedValue, ddlGuaRule.SelectedValue, ddlCxlRule.SelectedValue,
                dtStart, dtEnd, iWeek, base.BasUserName);


            if (b)
                Response.Write(CFun.AlertMeg(Resources.Site.SystemAddSuccess, "back", ""));
            else
                Response.Write(CFun.AlertMeg(Resources.Site.SystemError, "back", ""));

        }

        /// <summary>
        /// 检查冲突
        /// </summary>
        /// <param name="StartDate">开始日期</param>
        /// <param name="EndDate">结束日期</param>
        /// <param name="PlanList">价格代码组</param>
        /// <param name="SeasonID">季节段ID</param>
        /// <returns></returns>
        private string CheckPlanLevel(string StartDate, string EndDate, string PlanList, string SeasonID)
        {
            string strJson = "{\"coll\":";

            PlanList = PlanList.TrimEnd(',');

            if (!string.IsNullOrEmpty(PlanList))
            {
                string[] strPlan = PlanList.Split(',');

                Bll.AIR.InventoryPlan invPlan = new EZCRS.HCMS.Bll.AIR.InventoryPlan();

                DateTime dt1 = new DateTime();
                DateTime dt2 = new DateTime();

                if (string.IsNullOrEmpty(SeasonID))
                {

                    if (DateTime.TryParse(StartDate, out dt1))
                    {
                        if (DateTime.TryParse(EndDate, out dt2))
                        {

                        }
                    }

                }
                else
                {
                    //season id
                }

                List<string> lstPlan = new List<string>();

                foreach (string plan in strPlan)
                {
                    lstPlan.Add(plan);

                    //string [] str = plan.Split('-');

                    //string strRoomCode = str[0];
                    //string strPlanCode = str[1];
                }

                //check
                string str = invPlan.IsCollision(base.BasPropertyId, lstPlan, dt1, dt2);

                if (!string.IsNullOrEmpty(str))
                {
                    strJson += "\"" + str + "\"";
                }
                else
                {
                    strJson = "{\"coll\":\"\"";
                }
            }

            strJson += "}";

            return strJson;
        }


        /// <summary>
        /// 检查房型级别
        /// </summary>
        /// <param name="StartDate"></param>
        /// <param name="EndDate"></param>
        /// <param name="PlanList"></param>
        /// <param name="RoomCode"></param>
        /// <returns></returns>
        private string CheckRoomLevel(string StartDate, string EndDate, string PlanList, string RoomCodeList)
        {
            string strJson = "{\"coll\":";

            PlanList = PlanList.TrimEnd(',');
            RoomCodeList = RoomCodeList.TrimEnd(',');

            if (!string.IsNullOrEmpty(PlanList))
            {

                string[] strRooms = RoomCodeList.Split(',');
                string[] strPlan = PlanList.Split(',');

                Bll.AIR.InventoryPlan invPlan = new EZCRS.HCMS.Bll.AIR.InventoryPlan();

                DateTime dt1 = new DateTime();
                DateTime dt2 = new DateTime();

                if (DateTime.TryParse(StartDate, out dt1))
                {
                    if (DateTime.TryParse(EndDate, out dt2))
                    {

                    }
                }

                List<string> lstRatePlan = new List<string>();

                foreach (string room in strRooms)
                {

                    foreach (string plan in strPlan)
                    {
                        string str = room + "-" + plan;

                        lstRatePlan.Add(str);
                    }
                }

                string col = invPlan.IsCollision(base.BasPropertyId, lstRatePlan, dt1, dt2);

                if (!string.IsNullOrEmpty(col))
                {
                    strJson += "\"" + col + "\"";

                }
                else
                {
                    strJson = "{\"coll\":\"\"";
                }

                //foreach (string room in strRooms)
                //{
                //    if (bBreak) break;

                //    foreach (string plan in strPlan)
                //    {
                //        string strPlanCode = plan;

                //        //check
                //        bool b = invPlan.IsCollision(base.BasPropertyId, room, strPlanCode, dt1, dt2);


                //    }
                //}
            }

            strJson += "}";

            return strJson;
        }
    }
}
